import axios from 'axios'
import { api } from '../config'
import router from '../router'
import store from '../store'

export default {
  install(Vue) {
    axios.defaults.baseURL = api
    axios.defaults.headers.get['Content-Type'] = 'application/json'
    axios.defaults.headers.get['Accept'] = 'application/json; charset=utf-8, text/plain, */*'
    axios.defaults.headers.post['Content-Type'] = 'application/json'
    axios.defaults.headers.post['Accept'] = 'application/json,application/vnd.ms-excel; charset=utf-8, text/plain, */*'
    axios.defaults.headers.put['Content-Type'] = 'application/json'
    axios.defaults.headers.put['Accept'] = 'application/json; charset=utf-8, text/plain, */*'
    axios.defaults.withCredentials = true
    const nonAuthUrl = ['/auth?tokenKey=get', '/auth/login', 'auth/retrievePassword']
    axios.interceptors.request.use(config => {
      if (config.isLoadState) {
        config.loadState = config.isLoadState.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      }
      let isNonAuth = true
      // 判断接口是否需要认证信息
      nonAuthUrl.forEach(function (currentValue) {
        if (config.url.indexOf(currentValue) !== -1) {
          isNonAuth = false
        }
      })
      if (!isNonAuth) {
        return config
      }
      // 判断Header里是否有认证信息
      if (!config.headers.authorization || !config.headers.deviceId) {
        const account = window.localStorage.getItem('account')
        if (account) {
          const { jwt } = JSON.parse(account)
          config.headers.authorization = jwt
          config.headers.deviceId = window.localStorage.getItem('uuid')
        } else {
          router.push({ path: '/login' })
        }
      }
      return config
    })

    axios.interceptors.response.use(response => {
      if (response.config.loadState) {
        response.config.loadState.close()
      }
      if (response.data.type === 'application/vnd.ms-excel') {
        return response
      }

      const { meta, data } = response.data
      const { code, msg } = meta
      if (code === 1005) {
        // 刷新TOKEN
        const info = window.localStorage.getItem('account')
        const infoObj = JSON.parse(info)
        infoObj.jwt = data.jwt
        window.localStorage.setItem('account', JSON.stringify(infoObj))
        store.commit('account', infoObj)
        response.config.headers.authorization = data.jwt
        // 重新请求
        axios(response.config)
      } else if (code === 1006) {
        window.localStorage.removeItem('account')
        store.commit('account', {})
        Vue.prototype.$message.error('登录过期，请重新登录')
        setTimeout(() => {
          router.push({ path: '/login' })
        }, 500)
      } else if (code === 1008) {
        Vue.prototype.$message.error('该用户没有权限')
      } else if (code === -1) {
        Vue.prototype.$message.error(msg)
        return Promise.reject()
      }
      data.meta = meta
      return Promise.resolve(data)
    }, error => {
      Vue.prototype.$message.error('网络请求失败')
      return Promise.reject(error)
    })

    Vue.prototype.$http = axios
    Vue.http = axios
  },
  $http: axios
}

export const $http = axios
